package com.haois.ws.common.util;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * Created by RuiHaoZ on 2018/03/23.
 * 文件转换类
 */
public final class FileUpLoadUtil {

    private static Logger logger = LoggerFactory.getLogger(FileUpLoadUtil.class);

    public static void upload(MultipartFile file, String uploadDir) {
        String rename = file.getOriginalFilename();
        upload(file, uploadDir, rename);
    }

    /**
     * 上传文件服务类
     *
     * @param file      原始上传文件
     * @param uploadDir 文件存放目录
     * @param fileName  文件名
     * @return
     */
    public static String upload(MultipartFile file, String uploadDir, String fileName) {
        File desc = null;
        File dir = new File(uploadDir);
        try {
            if (!dir.exists()) {
                dir.mkdirs();
                logger.info("文件存放目录{}不存在，开始新建目录。", uploadDir);
            }
            desc = new File(dir, fileName);
            file.transferTo(desc);
        } catch (IOException e) {
            logger.error("上传文件出错，错误详情：{}", e.getMessage());
        }
        logger.info("上传到服务器的地址为:{}",uploadDir+fileName);
        return uploadDir+fileName;
    }

    public static File copyInputStreamToFile(MultipartFile multipartFile) throws IOException {
        File file = new File("C:\\Users\\haol\\Desktop\\图片库\\二维码\\gcu.jpg");
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
        return file;
    }

    public static File toFile(MultipartFile multipartFile) throws IOException {

        CommonsMultipartFile cf = (CommonsMultipartFile) multipartFile;
        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
        File file = fi.getStoreLocation();
        return file;
    }

    public static File transferTo(MultipartFile multipartFile) throws IOException {
        File file = new File("C:\\Users\\haol\\Desktop\\图片库\\二维码\\gcu.jpg");
        multipartFile.transferTo(file);
        return file;
    }

    /**
     * 此方法可转换为临时文件
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public static File toTmpFile(MultipartFile multipartFile) throws IOException {
        File file = null;
        try {
            String prefix = "tmp";
            String suffix = null;
            //suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
            file = File.createTempFile(prefix, suffix);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

}
